﻿using System;
using System.Collections.Generic;
using System.Text;
using xReplace;
using ICSharpCode.SharpZipLib;
using System.IO;

namespace ZipPlugin
{
    class ZipCommand : AbstractProcessingCommand
    {
        public ZipCommand(ref Content pipes)
            : base(ref pipes)
        { }

        public override bool ProcessCommand(System.Xml.XmlNodeList param)
        {
            string renameRules = this.GetNodeValue("renamerules", param);
            string outputPath = this.GetNodeValue("outpath", param);
            string ext = this.GetNodeValue("extension", param);
            ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();

            string baseFilename = this.contentPipelines.RelativeFilename;
            string zipFilename = Path.GetFileNameWithoutExtension(baseFilename) + "." + ext;
            string outputDir = Path.GetDirectoryName(Path.Combine(outputPath,baseFilename));
            if (renameRules != "")
                zipFilename = RenameHelper.PerformRename(zipFilename, renameRules, this.contentPipelines);
            string finalFilename = Path.Combine(outputDir,zipFilename);

            
            contentPipelines.StoreContent("$$ZIP_FILENAME", zipFilename);
            contentPipelines.StoreContent("$$ZIP_ABSOLUTE_PATH", outputDir);
            contentPipelines.StoreContent("$$ZIP_RELATIVE_PATH", Path.GetDirectoryName(baseFilename));

            if(!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir);            
            z.CreateZip(finalFilename, Path.GetDirectoryName(this.contentPipelines.AbsoluteFilename), false, Path.GetFileName(this.contentPipelines.AbsoluteFilename));
            return true;
        }
    }
}
